package com.sgb.kjwl.viewmodel.self;


import android.text.TextUtils;
import android.widget.Toast;

import androidx.databinding.ObservableField;

import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.businessmanagement.CompanyEntity;
import com.sgb.kjwl.model.entity.user.UserBaseEntity;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.ListResponse;
import com.sgb.kjwl.repository.SelfRepertory;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.event.self.UploadAvatarEvent;
import com.sgb.kjwl.view.ui.activity.self.PersonInfoActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PersonInfoModel extends BaseViewModel {
    private PersonInfoActivity activity;
    private SelfRepertory repertory;

    public ObservableField<UserMsgEntity> userInfo = new ObservableField<>();
    public ObservableField<UserBaseEntity> userBaseEntity = new ObservableField<>();
    private List<BaseAreaEntity> sexList = new ArrayList<>();

    //PersonInfoModel有参方法
    public PersonInfoModel(PersonInfoActivity activity, SelfRepertory repertory) {
        this.activity = activity;
        this.repertory = repertory;
    }

    public void getBaseArea() {
        DialogHelper.showProgressDialog(activity, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getBaseArea().enqueue(new Callback<BaseEntity<List<BaseAreaEntity<List<BaseAreaEntity<List<BaseAreaEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<BaseAreaEntity<List<BaseAreaEntity<List<BaseAreaEntity>>>>>>> call, Response<BaseEntity<List<BaseAreaEntity<List<BaseAreaEntity<List<BaseAreaEntity>>>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getData() != null) {
//                    activity.setPopData(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<BaseAreaEntity<List<BaseAreaEntity<List<BaseAreaEntity>>>>>>> call, Throwable t) {

            }
        });
    }

    public void getEssentialInformation() {
        DialogHelper.showProgressDialog(activity, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().userInfoDetail().enqueue(new Callback<BaseEntity<UserBaseEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserBaseEntity>> call, Response<BaseEntity<UserBaseEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getData() != null) {
                    userBaseEntity.set(response.body().getData());
                    activity.showHeadPortrait(response.body().getData());
                } else {
                    userBaseEntity.set(new UserBaseEntity());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserBaseEntity>> call, Throwable t) {
                userBaseEntity.set(new UserBaseEntity());
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });
    }

    public void editBasicInfo() {
        DialogHelper.showProgressDialog(activity, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().editBasicInfo(userBaseEntity.get()).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals("ok")) {
                    Toast.makeText(activity, "保存成功", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                MToast.showToast(activity, t.getMessage());
            }
        });
    }


    /**
     * 公司列表信息
     */
    public void getCompanyList(int page,int limit) {
        APIManager.getInstance().getMailListAPI().getNewCurrentCompany(limit+"", page+"").enqueue(new ICallBack<BaseEntity<ListResponse<List<CompanyEntity>>>>(true, true) {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<CompanyEntity>>> data) {
                activity.showCompanyList(data.getData().getList());
            }
        });
    }

    /**
     * 设置主企业接口
     */
    public void setMainCompany(CompanyEntity companyEntity) {
        APIManager.getInstance().getMailListAPI().setMainCompany(companyEntity.getId(), companyEntity.getMemberNo()).enqueue(new ICallBack<BaseEntity>(true, true) {
            @Override
            public void onSuccess(BaseEntity data) {
                MToast.showToast(activity, "设置主企业成功");
                getCompanyList(1,10);
            }
        });
    }

    //     //获取用户信息
//    public void getUserInfo() {
//        //打开弹窗
//        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
//        //网络请求用户信息
//        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
//            //成功反馈
//            @Override
//            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
//                //关闭弹窗
//                DialogHelper.dismissProgressDialog();
//                //判断参数为空时，停止返回
//                if (response.body() == null || response.body().getData() == null) {
//                    return;
//                }
//                //之前的人写的，不太明白放入集合而未调用
//                userInfo.set(response.body().getData());
//                //判断一切网络请求正常
//                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
//                    if (response.body().getData().getEnterpriseAuth().equals(AppConstant.STATUS_SUCCESS_STR)) {
//                        //企业认证成功
////                        activity.companySuccess(response.body().getData().getEnterprise().getId());
//                    } else {
//                        //todo 测试 暂时加上店铺id
//                        //activity.companyFail(response.body().getData().getEnterprise().getId());
//                    }
//
//                } else {
//                    MToast.showToast(activity, response.body().getMsg());
//                }
//            }
//            //失败反馈
//            @Override
//            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
//                //关闭弹窗
//                DialogHelper.dismissProgressDialog();
//            }
//        });
//    }
/*    public void getCompanyList() {
        APIManager.getInstance().getMailListAPI().getCurrentCompany().enqueue(new Callback<BaseEntity<List<CompanyEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<CompanyEntity>>> call, Response<BaseEntity<List<CompanyEntity>>> response) {
                if (response.body() == null) return;
                if (response.body().getState().equals("ok") && response.body().getData() != null && response.body().getData().size() > 0) {
                    activity.showCompanyList(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<CompanyEntity>>> call, Throwable t) {

            }
        });
    }*/

    public void uploadAvatar(File file) {
//        activity.showProbar();
        //创建map集合
        Map<String, RequestBody> photos = new HashMap<>();
        //将文件转换成多媒体文件，方便上传
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + file.getName() + "image.jpg\"", requestBody);
        //DialogHelper.showProgressDialog(activity, null, "头像上传中...", 0, false, null).setCanceledOnTouchOutside(true);
        //接口请求
        APIManager.getInstance().getUploadAPI().uploadImg(photos).enqueue(new Callback<BaseEntity>() {
            //成功响应
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                //将最新的头像地址保存在sp中
//                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.AVATAR,);
////                activity.hideProbar();
//                response.get().setImage(avatar);
                //请求完毕，关闭弹窗
                DialogHelper.dismissProgressDialog();
                if (response == null || response.body() == null || response.body().getData() == null){
                    MToast.showToast(activity, "上传失败");
                    return;
                }
                //传给activity展示头像
                if (response.body().getData() == null) {
                    userBaseEntity.get().setImage("");
                    activity.showAvatar("");
                } else {
                    if (!TextUtils.isEmpty(response.body().getData().toString())){
                        userBaseEntity.get().setImage(response.body().getData().toString());
                        activity.showAvatar(response.body().getData().toString());
                        //吐司上传成功
                        MToast.showToast(activity, "头像上传成功");
                        //Event触发更新事件
                        UploadAvatarEvent uploadAvatarEvent = new UploadAvatarEvent();
                        uploadAvatarEvent.setMessageTag(EventConstant.EVENT_UPLOAD_AVATAR);
                        EventBus.getDefault().postSticky(uploadAvatarEvent);
                    }else {
                        userBaseEntity.get().setImage("");
                        activity.showAvatar("");
                    }
                }
                EventBus.getDefault().postSticky(LoginEvent.make(EventConstant.EVENT_MAIN_INDEX, ""));
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                MToast.showToast(activity, "上传失败");
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public List<BaseAreaEntity> getSexList() {
        if (sexList.size() == 0) {
            BaseAreaEntity boy = new BaseAreaEntity();
            BaseAreaEntity girl = new BaseAreaEntity();
            boy.setNo("0");
            boy.setName("男");
            girl.setNo("1");
            girl.setName("女");
            sexList.add(boy);
            sexList.add(girl);
        }
        return sexList;
    }
}
